import { Component, AfterViewInit, HostBinding } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    selector: 'app-index-tmpl',
    templateUrl: './index-tmpl.component.html',
    styleUrls: ['./index-tmpl.component.css']
})
export class IndexTmplComponent implements AfterViewInit {
    @HostBinding('class.f-utils-absolute-all') cls = true;

    @HostBinding('class.f-utils-flex-column') cls1 = true;

    isStylesReady = false;

    themeName: string;

    themeSize: string;

    // widgetName: string;
    colorTheme: string;
    // typographyClass: string;

    constructor(private router: Router) {
        const THEME_POSITION = 2;
        const COLOR_THEME_POSITION = 3;
        //url:/preview-page/farris/green-default
        const urlParts = this.router.url.split('/');
        this.themeName = urlParts[THEME_POSITION];
        const tColorTheme = urlParts[COLOR_THEME_POSITION].split('-');
        if (tColorTheme.length > 1) {
            this.colorTheme = tColorTheme[0];
            this.themeSize = tColorTheme[1];
        } else {
            this.colorTheme = tColorTheme[0];
            this.themeSize = 'default';
        }
    }

    receiveMessage(e: any): void {
        if (e.data && e.data.name) {
            // 根据内容
            this.addHeadStyles(e.data.css, e.data.name);
            // themeSize在framework和Farris下都会有
            this.themeSize = e.data.themeSize;
        }
    }

    /**
     * 追加通过变量生成的样式
     * <style type="text/css" id="dynamic-styles">
     * </style>
     * @param css
     */
    addHeadStyles(css: string, themeName: string): void {
        const head = document.getElementsByTagName('head')[0];
        const style = document.createElement('style');
        const DYNAMIC_STYLES_ID = 'dynamic-styles-' + themeName;

        const dynamicStylesElement = document.getElementById(DYNAMIC_STYLES_ID);

        if ((!css && dynamicStylesElement) || dynamicStylesElement) {
            dynamicStylesElement.parentNode.removeChild(dynamicStylesElement);
        }
        if (css) {
            style.type = 'text/css';
            style.id = DYNAMIC_STYLES_ID;

            // 可以再次调整已生成的样式
            // css = css
            //   .replace(//gi, 'content/css/icons/dxicons')

            style.appendChild(document.createTextNode(css));
            head.appendChild(style);
            // 当样式已经加载成功
            this.isStylesReady = true;
        }
    }

    private insterAfter(newElement, targetElement) {
        const parent = targetElement.parentNode;
        if (parent.lastChild === targetElement) {
            parent.appendChild(newElement);
        } else {
            parent.insertBefore(newElement, targetElement.nextSibling);
        }
    }

    /**
     * 添加link比追加css方式节省性能
     */
    private addHeadLinks(linkId, insertAfterId): void {
        if (this.colorTheme !== 'default' || (this.themeSize !== 'default' && linkId === 'dynamic-farris')) {
            const head = document.getElementsByTagName('head')[0];
            const linkEl = document.createElement('link');
            const DYNAMIC_LINKS_ID = linkId;
            // 应该不存在这种场景
            const dynamicLinksElement = document.getElementById(DYNAMIC_LINKS_ID);
            if (dynamicLinksElement) {
                dynamicLinksElement.parentNode.removeChild(dynamicLinksElement);
            }
            linkEl.rel = 'stylesheet';
            linkEl.id = DYNAMIC_LINKS_ID;
            if (linkId === 'dynamic-framework') {
                linkEl.href = 'assets/framework/themes/' + this.colorTheme + '/gsp-cloud-web.css';
            } else {
                linkEl.href = 'assets/themes/' + this.colorTheme + '/' + this.themeSize + '/farris-all.css';
            }
            this.insterAfter(linkEl, head.querySelector('#' + insertAfterId));
        }
    }

    ngAfterViewInit(): void {
        this.addHeadLinks('dynamic-farris', 'farrisThemeLink');
        this.addHeadLinks('dynamic-framework', 'frameworkThemeLink');
        const messageListener = this.receiveMessage.bind(this);
        window.removeEventListener('message', messageListener);
        // 捕获到message事件的时候，执行style的加载方法
        window.addEventListener('message', messageListener, false);
        // 通知父级，关闭loading
        window.parent.postMessage({ hideLoading: true }, window.parent.location.href);
    }
}
